package com.lwl.crm.settings.service.impl;

import com.lwl.crm.exception.LoginException;
import com.lwl.crm.settings.entity.User;
import com.lwl.crm.settings.mapper.UserMapper;
import com.lwl.crm.settings.service.UserService;
import com.lwl.crm.utils.MD5Util;
import com.lwl.crm.utils.SqlSessionUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * user业务具体实现
 */
public class UserServiceImpl implements UserService {

    protected  UserMapper userMapper =
            SqlSessionUtil.getSqlSession()
            .getMapper(UserMapper.class);

    /**
     * 登录功能
     * @param loginAct
     * @param loginPwd
     * @param ip
     * @return
     */
    @Override
    public User login(String loginAct, String loginPwd, String ip) throws LoginException {
        //加密密码
        String pwd = MD5Util.getMD5(loginPwd);
        //保存参数
        Map<String,String> map = new HashMap<>();
        map.put("loginAct",loginAct);
        map.put("loginPwd",pwd);
        //获取UserService对象

        User user = userMapper.login(map);
        //登录验证
        if(user != null) {
            //验证账号是否上锁
            if(!"0".equals(user.getLockState())){
                //验证ip
                if (user.getAllowIps().contains(ip)){
                    return user;
                }
                throw new LoginException("ip受限");
            }
            throw new LoginException("账号已锁");
        }
        throw new LoginException("账号或密码错误");
    }
}
